package com.szholly.plug.activity.runtime;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.ManagementService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.bpmn.behavior.UserTaskActivityBehavior;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmActivity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.task.TaskDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.szholly.plug.activity.core.BpmException;
import com.szholly.plug.activity.core.Constants;
import com.szholly.plug.activity.interceptor.BpmHandleOptionBase;
import com.szholly.plug.activity.interceptor.BpmWaitOptionBase;
import com.szholly.plug.activity.interceptor.OptionInfo;
import com.szholly.plug.activity.model.BpmConfigCache;
import com.szholly.plug.activity.model.BpmConfigEditInterceptor;
import com.szholly.plug.activity.model.BpmConfigRow;
import com.szholly.plug.activity.model.BpmHistoryRow;
import com.szholly.plug.activity.model.BpmHistoryTable;
import com.szholly.plug.activity.model.BpmTaskConfigRow;
import com.szholly.utils.util.StringUtils;
import com.szholly.data.general.GlobalDataType;
import com.szholly.data.general.IQueryMap;
import com.szholly.data.general.ITable;
import com.szholly.data.general.QueryMap;
import com.szholly.data.general.RowBase;
import com.szholly.plug.safe.entity.user.UserEntity;
import com.szholly.plug.safe.entity.user.UserService;

/**
 * 定义工作流实例操作组件
 */
@Component
public class WorkFlowCompont implements IWorkFlowCompont {

	private static Logger logger = Logger.getLogger(WorkFlowCompont.class);
	
	/**
	 * 流程Engine
	 */
	@Autowired(required = false)
	protected ProcessEngine processEngine;

	/**
	 * 运行时服务
	 */
	@Autowired(required = false)
	private RuntimeService runtimeService;

	/**
	 * 流程任务服务
	 */
	@Autowired(required = false)
	protected TaskService taskService;

	/**
	 * 流程管理服务
	 */
	@Autowired(required = false)
	protected ManagementService managementService;

	/**
	 * 流程部署服务
	 */
	@Autowired(required = false)
	protected RepositoryService repositoryService;

	/**
	 * 流程历史服务
	 */
	@Autowired(required = false)
	protected HistoryService historyService;

	/**
	 * 角色用户定义服务
	 */
	@Autowired(required = false)
	private IdentityService identityService;
	
	/**
	 * 启动流程 默认规则为：流程启动后直接跳过第一个用户任务节点
	 * 
	 * @param rowBase
	 * @param userEntity
	 *            当前用户
	 */
	@Override
	public void onlyStart(ITable pTable, RowBase rowBase, UserEntity userEntity, String activitiKey) {
		// 启动流程
		Map<String, Object> variables = new HashMap<String, Object>();
		ProcessInstance processInstance = runtimeService
				.startProcessInstanceByKey(activitiKey, variables);
		String exeId = processInstance.getId();
		// 设置流程实例ID
		rowBase.setValue(Constants.FIELD_PROID, exeId);
		// 其它配置
		rowBase.setValue(Constants.FIELD_DEFINID, activitiKey);
		BpmConfigRow configRow = BpmConfigCache.getConfig(activitiKey);
		if(configRow!=null){
			rowBase.setValue(Constants.FIELD_FORMURL, configRow.getSFormurl());
			rowBase.setValue(Constants.FIELD_FORMNAME, configRow.getFormName());
			rowBase.setValue(Constants.FIELD_FORMPOPID, configRow.getFormPopId());
		}
		
		// 流程发启人
		rowBase.setValue(Constants.FIELD_APPLYNAME, userEntity.getUserID());
		
		List<Task> nextTasks = findActiveTasksByProId(exeId);
		if (nextTasks.size() == 1) {
			Task nextTask = nextTasks.get(0);

			// 记录第一个节点信息
			getActiveTasksInfo(activitiKey, nextTasks, rowBase, exeId, null, userEntity);
			
			// 处理完
			handelOption(pTable, rowBase, "创建", "<空>", 
					userEntity.getUserID(), userEntity.getUserRealName(), 
					nextTask.getId(), "",
					"U0", "起点", true, this);
		} else {
			throw new BpmException("未处理多用户任务节点！");
		}
	}

	/**
	 * 启动流程 默认规则为：流程启动后直接跳过第一个用户任务节点
	 * 
	 * @param rowBase
	 * @param userEntity
	 *            当前用户
	 */
	@Override
	public void start(ITable pTable, RowBase rowBase, UserEntity userEntity, String activitiKey) {
		// 启动流程
		Map<String, Object> variables = new HashMap<String, Object>();
		ProcessInstance processInstance = runtimeService
				.startProcessInstanceByKey(activitiKey, variables);
		String exeId = processInstance.getId();
		// 设置流程实例ID
		rowBase.setValue(Constants.FIELD_PROID, exeId);
		// 其它配置
		rowBase.setValue(Constants.FIELD_DEFINID, activitiKey);
		BpmConfigRow configRow = BpmConfigCache.getConfig(activitiKey);
		if(configRow!=null){
			rowBase.setValue(Constants.FIELD_FORMURL, configRow.getSFormurl());
			rowBase.setValue(Constants.FIELD_FORMNAME, configRow.getFormName());
			rowBase.setValue(Constants.FIELD_FORMPOPID, configRow.getFormPopId());
		}
		
		// 流程发启人
		rowBase.setValue(Constants.FIELD_APPLYNAME, userEntity.getUserID());
					
		List<Task> nextTasks = findActiveTasksByProId(exeId);
		if (nextTasks.size() == 1) {
			Task nextTask = nextTasks.get(0);

			// 记录第一个节点信息
			getActiveTasksInfo(activitiKey, nextTasks, rowBase, exeId, null, userEntity);
			
			// 处理完
			handelOption(pTable, rowBase, "创建", "<空>", 
					userEntity.getUserID(), userEntity.getUserRealName(), 
					nextTask.getId(), "",
					"U0", "起点", true, this);
			
			// 完成当前任务
			comTask(pTable, activitiKey, exeId, nextTask, rowBase, userEntity);
		} else {
			throw new BpmException("未处理多用户任务节点！");
		}
	}

	/**
	 * 流程撤销
	 * 
	 * @param exeId
	 * @param rowBase
	 * @param userEntity
	 */
	@Override
	public void revoke(ITable pTable, String pDefId, String exeId, RowBase rowBase,
			UserEntity userEntity) {

		List<Task> nextTasks = findActiveTasksByProId(exeId);
		String taskDefinitionKey = "";
		String taskId = "";
		String taskName = "";
		
		if (nextTasks.size() == 1) {
			Task nextTask = nextTasks.get(0);

			// 流程状态名称
			rowBase.setValue(Constants.FIELD_TASK_STATE, "结束");
			rowBase.setValue(Constants.FIELD_TASK_ID, "U9");
			rowBase.setValue(Constants.FIELD_TASK_ASSIGNEES, "");
			BpmTaskConfigRow configRow = BpmConfigCache.getTaskConfig(pDefId, "U9");
			if (configRow != null) {
				rowBase.setValue(Constants.FIELD_CANDEL, configRow.getTaskCanDel());
			} else {
				rowBase.setValue(Constants.FIELD_CANDEL, "0");
			}
			taskDefinitionKey = nextTask.getTaskDefinitionKey();
			taskId = nextTask.getId();
			taskName = nextTask.getName();
		} else if (nextTasks.size() > 1) {
			for(Task task : nextTasks){
				taskDefinitionKey += task.getTaskDefinitionKey() + ",";
				taskId += task.getId() + ",";
				taskName += task.getName() + ",";
			}
			taskDefinitionKey = taskDefinitionKey.substring(0, taskDefinitionKey.length()-1);
			taskName = taskName.substring(0, taskName.length()-1);
		}
		
		// 处理完
		handelOption(pTable, rowBase, "撤销", "<空>", 
				userEntity.getUserID(), userEntity.getUserRealName(), 
				"", taskId, 
				taskDefinitionKey, taskName, false, this);

		// 删除流程实例
		delete(exeId);
	}
	
	/**
	 * 删除流程
	 */
	private void delete(String exeId) {
		// 流程已经结束
		ProcessInstance processInstance = runtimeService
				.createProcessInstanceQuery().processInstanceId(exeId)
				.singleResult();
		if (processInstance == null) {
			return;
		}

		// 先挂起流程实例
		runtimeService.suspendProcessInstanceById(exeId);
		// 删除流程实例
		runtimeService.deleteProcessInstance(exeId, "");
		// 删除当前任务
		historyService.deleteHistoricProcessInstance(exeId);
	}

	/**
	 * 处理用户任务
	 */
	@Override
	public void complete(ITable pTable, String activitiKey, String exeId, RowBase rowBase,
			UserEntity userEntity) {
		List<Task> nextTasks = findActiveTasksByProId(exeId);
		if (nextTasks.size() == 1) {
			Task nextTask = nextTasks.get(0);
			comTask(pTable, activitiKey, exeId, nextTask, rowBase, userEntity);
		} else if (nextTasks.size() > 1) {
			String tjTask = (String)rowBase.getValue(GlobalDataType.String, Constants.FIELD_TJTASKS);
			if(StringUtils.IsNullOrSpace(tjTask)){
				throw new BpmException("未确定提交节点！");
			}
			for(Task task : nextTasks){
				if(tjTask.contains(task.getTaskDefinitionKey())){
					comTask(pTable, activitiKey, exeId, task, rowBase, userEntity);
				}
			}
		}
	}

	/**
	 * 流程撤回
	 * 
	 * @param exeId
	 * @param rowBase
	 * @param userEntity
	 */
	@Override
	public void reback(ITable pTable, String pDefId, String exeId, RowBase rowBase,
			UserEntity userEntity) {
		// 流程已经结束
		ProcessInstance processInstance = runtimeService
				.createProcessInstanceQuery().processInstanceId(exeId)
				.singleResult();
		if (processInstance == null) {
			throw new BpmException("流程已经结束，不可以撤回！");
		}

		// 之前的审批节点与用户
		String ptaskUser = (String) rowBase.getValue(GlobalDataType.String,
				Constants.FIELD_PTASKUSER);
		if (StringUtils.IsNullOrSpace(ptaskUser)) {
			throw new BpmException("当前用户没有撤回权限！");
		}
		
		String[] historys = ptaskUser.split("&");
		String last = historys[historys.length-1];
		String[] lastMsg = last.split("~");
		String taskUserMsg = lastMsg[0];
		String[] taskUser = taskUserMsg.split(",");
		if (taskUser.length != 3) {
			throw new BpmException("当前用户没有撤回权限！");
		}
		String taskname = taskUser[0];
		String user = taskUser[2];
		// 超级管理员可审批所有流程
		if (!userEntity.getIsSuperAdmin()
				&& !user.equals(userEntity.getUserID())) {
			throw new BpmException("当前用户没有【" + taskname + "】的撤回权限！");
		}
		
		// 记录节点状态
		String pTaskName = (String)rowBase.getValue(GlobalDataType.String, Constants.FIELD_TASK_STATE);
		String pTaskDefinitionKey = (String)rowBase.getValue(GlobalDataType.String, Constants.FIELD_TASK_ID);
		String pTaskId = "";
		
		List<Task> nextTasks = findActiveTasksByProId(exeId);
		if (nextTasks.size() == 1) {
			pTaskId = nextTasks.get(0).getId();
		} else if (nextTasks.size() > 1) {
			for(Task task : nextTasks){
				pTaskId += task.getId() + ",";
			}
			pTaskId = pTaskId.substring(0, pTaskId.length()-1);
		} 
				
		// 撤回流程
		jump(exeId, taskname);

		// 撤回数据
		String pTaskUser = (String)rowBase.getValue(GlobalDataType.String, Constants.FIELD_PTASKUSER);
		if(!StringUtils.IsNullOrSpace(pTaskUser)){
			String[] history = pTaskUser.split("&");
			String last2 = history[history.length-1];
			String oldHistory = "";
			for(int i=0;i<history.length-1;i++){
				oldHistory += history[i] + "&";
			}
			if(oldHistory!=""){
				oldHistory = oldHistory.substring(0, oldHistory.length()-1);
			}
			rowBase.setValue(Constants.FIELD_PTASKUSER, oldHistory);
			setRowState(rowBase, last2);
		}

		nextTasks = findActiveTasksByProId(exeId);
		String taskId = "";
		for(Task task : nextTasks){
			List<String> listCopy = new ArrayList<String>();
			getTaskAssignees(rowBase, 
					task.getTaskDefinitionKey(), listCopy);
			taskService.setAssignee(task.getId(), listCopy.get(0));
			for (int i = 1; i < listCopy.size(); i++) {
				taskService.addCandidateUser(task.getId(),
						listCopy.get(i));
			}
			taskId += task.getId() + ",";
		}
		if(taskId!=""){
			taskId = taskId.substring(0, taskId.length()-1);
		}

		// 处理完
		handelOption(pTable, rowBase, "撤回", "<空>", 
				userEntity.getUserID(), userEntity.getUserRealName(), 
				taskId, pTaskId,
				pTaskDefinitionKey, pTaskName, true, this);
	}

	/**
	 * 交办
	 * 
	 * @param pDefId
	 * @param exeId
	 * @param rowBase
	 * @param userEntity
	 */
	@Override
	public void assignedBy(ITable pTable, String pDefId, String exeId, RowBase rowBase,
			UserEntity userEntity) {
		List<Task> nextTasks = findActiveTasksByProId(exeId);
		if (nextTasks.size() == 1) {
			Task task = nextTasks.get(0);
			// 验让当前用户是否有当前节点的审批权限
			checkTaskAssignees(rowBase, userEntity, pDefId, task);
			
			HashMap<String, String> userMap = new HashMap<String, String>();
			// 交办给谁, userid,username
			String taskUsers = (String) rowBase.getValue(GlobalDataType.String,
					Constants.FIELD_JBUSER);
			String[] jbUser = taskUsers.split(",");
			userMap.put(jbUser[0], jbUser[1]);
			
			// 处理其它人
			String assignees = getTaskAssignees(rowBase, task.getTaskDefinitionKey(), null);
			String[] users = assignees.split(",");
			if(users.length > 0){
				for(int i=0; i<users.length; i+=2){
					String userId = users[i];
					String userName = users[i+1];
					if(!userEntity.getUserID().equals(userId)){
						userMap.put(userId, userName);
					}
				}
			}
			
			// 记录交办人
			Set<String> userList = userMap.keySet();
			String userString = task.getTaskDefinitionKey() + "," + task.getName() + ",";
			for (String item : userList) {
				userString += item + "," + userMap.get(item) + ",";
			}
			if(userString!=""){
				userString = userString.substring(0, userString.length() - 1);
			}
			rowBase.setValue(Constants.FIELD_TASK_ASSIGNEES, userString);
			
			// 修改流程数据
			List<String> listCopy = new ArrayList<String>();
			listCopy.addAll(userList);
			// 设置任务的执行人
			taskService.setAssignee(task.getId(), listCopy.get(0));
			// 添加任务的备选执行人
			for (int i = 1; i < listCopy.size(); i++) {
				taskService.addCandidateUser(task.getId(),
						listCopy.get(i));
			}
			
			// 记录审批历史
			String pTaskName = (String)rowBase.getValue(GlobalDataType.String, Constants.FIELD_TASK_STATE);
			String pTaskDefinitionKey = (String)rowBase.getValue(GlobalDataType.String, Constants.FIELD_TASK_ID);

			// 处理完
			handelOption(pTable, rowBase, "交办", jbUser[1], 
					userEntity.getUserID(), userEntity.getUserRealName(), 
					task.getId(), task.getId(),
					pTaskDefinitionKey, pTaskName, true, this);
		} else if (nextTasks.size() > 1) {
			throw new BpmException("未处理多用户任务节点！");
		}
	}

	/**
	 * 完成当前任务
	 * 
	 * @param task
	 * @param assignee
	 *            审批人
	 */
	private void comTask(ITable pTable, String pDefId, String exeId, Task task,
			RowBase rowBase, UserEntity user) {

		// 验让当前用户是否有当前节点的审批权限
		checkTaskAssignees(rowBase, user, pDefId, task);

		// 完成任务
		Map<String, Object> comValues = new HashMap<String, Object>();
		// 从表单对象中获取以flag_开头的字段值传给工作流
		Set<String> keys = rowBase.keySet();
		for (String key : keys) {
			if (key.startsWith("flag_")) {
				if (comValues.containsKey(key)) {
					comValues.remove(key);
				}
				comValues.put(key, rowBase.get(key));
			}
		}
		// 根据配置信息，中表单实体中获取字段信息
		BpmConfigRow configRow = BpmConfigCache.getConfig(pDefId);
		if (configRow != null) {
			String fromValues = configRow.getSFormvalue();
			if (!StringUtils.IsNullOrSpace(fromValues)) {
				String[] fields = fromValues.split(",");
				for (String field : fields) {
					if (rowBase.containsKey(field)) {
						if (comValues.containsKey(field)) {
							comValues.remove(field);
						}
						comValues.put(field, rowBase.get(field));
					}
				}
			}
		}
		
		// 获取审批历史中的字段信息
		String optionContent = "<空>";
		String option = "";
		// 审批内容(审批意见)
		if (rowBase.containsKey(BpmHistoryRow.FIELD_SOptioncontent)) {
			if (comValues.containsKey(BpmHistoryRow.FIELD_SOptioncontent)) {
				comValues.remove(BpmHistoryRow.FIELD_SOptioncontent);
			}
			comValues.put(BpmHistoryRow.FIELD_SOptioncontent,
					rowBase.get(BpmHistoryRow.FIELD_SOptioncontent));
			optionContent = (String) rowBase
					.get(BpmHistoryRow.FIELD_SOptioncontent);
		}
		// 审核操作(通过，不通过)
		if (rowBase.containsKey(BpmHistoryRow.FIELD_SOption)) {
			if (comValues.containsKey(BpmHistoryRow.FIELD_SOption)) {
				comValues.remove(BpmHistoryRow.FIELD_SOption);
			}
			comValues.put(BpmHistoryRow.FIELD_SOption,
					rowBase.get(BpmHistoryRow.FIELD_SOption));
			option = (String) rowBase
					.get(BpmHistoryRow.FIELD_SOption);
		}
		// 审批历史对应关系
		BpmTaskConfigRow taskConfig = BpmConfigCache.getTaskConfig(pDefId,
				task.getTaskDefinitionKey());
		if (taskConfig != null) {
			String history = taskConfig.getSHistoryconfig();
			if (!StringUtils.IsNullOrSpace(history)) {
				String[] fields = history.split(",");
				for (String fieldItem : fields) {
					String[] field = fieldItem.split("=");
					if (field.length == 2) {
						if (field[0].equals(BpmHistoryRow.FIELD_SOptioncontent)) {
							Object value = rowBase.get(field[1]);
							if (comValues
									.containsKey(BpmHistoryRow.FIELD_SOptioncontent)) {
								comValues
										.remove(BpmHistoryRow.FIELD_SOptioncontent);
							}
							comValues.put(BpmHistoryRow.FIELD_SOptioncontent,
									value);
							if (comValues.containsKey(field[1])) {
								comValues.remove(field[1]);
							}
							comValues.put(field[1], value);
							if(value!=null){
								optionContent = value.toString();
							}
						}
						if (field[0].equals(BpmHistoryRow.FIELD_SOption)) {
							Object value = rowBase.get(field[1]);
							if (comValues
									.containsKey(BpmHistoryRow.FIELD_SOption)) {
								comValues.remove(BpmHistoryRow.FIELD_SOption);
							}
							comValues.put(BpmHistoryRow.FIELD_SOption, value);
							if (comValues.containsKey(field[1])) {
								comValues.remove(field[1]);
							}
							comValues.put(field[1], value);
							option = (String) value;
						}
					}
				}
			}
		}

		// 设置任务的执行人
		taskService.setAssignee(task.getId(), user.getUserID());
		// 领取第一个任务
		taskService.claim(task.getId(), user.getUserID());
		// 完成任务
		taskService.complete(task.getId(), comValues);

		// 记录任务的完成人
		String rowState = getRowState(rowBase, task, user);
		
		// 处理接下来的任务
		List<Task> nextTasks = findActiveTasksByProId(exeId);
		getActiveTasksInfo(pDefId, nextTasks, rowBase, exeId, comValues, user);
		
		String oldRowState = (String)rowBase.getValue(GlobalDataType.String, Constants.FIELD_PTASKUSER);
		if(StringUtils.IsNullOrSpace(oldRowState)){
			oldRowState = rowState;
		}else{
			oldRowState += "&" + rowState;
		}
		rowBase.setValue(Constants.FIELD_PTASKUSER, oldRowState);

		// 处理完
		String taskId = "";
		for(Task taskItem : nextTasks){
			taskId += taskItem.getId() + ",";
		}
		if(taskId!=""){
			taskId = taskId.substring(0, taskId.length()-1);
		}
		handelOption(pTable, rowBase, option, optionContent, 
				user.getUserID(), user.getUserRealName(),
				taskId, task.getId(),
				task.getTaskDefinitionKey(), task.getName(), true, this);
	}

	private String getRowState(RowBase row, Task task, UserEntity user) {

		String rowState = "";
		// 上一节点的名称与审批人
		rowState = task.getTaskDefinitionKey() + "," + task.getId() + ","
				+ user.getUserID() + "~";
		
		// 当前用户任务ID
		String taskId = (String) row.getValue(GlobalDataType.String,
				Constants.FIELD_TASK_ID);
		if (StringUtils.IsNullOrSpace(taskId)) {
			rowState += "~";
		} else {
			rowState += taskId + "~";
		}

		// 当前用户任务名称
		String taskState = (String) row.getValue(GlobalDataType.String,
				Constants.FIELD_TASK_STATE);
		if (StringUtils.IsNullOrSpace(taskState)) {
			rowState += "~";
		} else {
			rowState += taskState + "~";
		}

		// 当前任务审批人
		String taskAssignees = (String) row.getValue(GlobalDataType.String,
				Constants.FIELD_TASK_ASSIGNEES);
		if (StringUtils.IsNullOrSpace(taskAssignees)) {
			rowState += "~";
		} else {
			rowState += taskAssignees + "~";
		}

		// 接下来的任务以及任务审批人
		String taskNextAssignees = (String) row.getValue(GlobalDataType.String,
				Constants.FIELD_NEXT_ASSIGNEES);
		if (StringUtils.IsNullOrSpace(taskNextAssignees)) {
			rowState += "~";
		} else {
			rowState += taskNextAssignees + "~";
		}

		// 流程参于者
		String assigneesUser = (String) row.getValue(GlobalDataType.String,
				Constants.FIELD_ASSIGNEE_USERS);
		if (StringUtils.IsNullOrSpace(assigneesUser)) {
			rowState += "~";
		} else {
			rowState += assigneesUser + "~";
		}

		// 流程是否可删除，默认为第一个节点时，可删除流程
		String canDel = (String) row.getValue(GlobalDataType.String,
				Constants.FIELD_CANDEL);
		if (StringUtils.IsNullOrSpace(canDel)) {
			rowState += "~";
		} else {
			rowState += canDel + "~";
		}

		return rowState;
	}
	
	private void setRowState(RowBase row, String rowState) {
		String[] rowMsgs = rowState.split("~");
		// 上一节点的名称与审批人
		// String pTaskUser = rowMsgs[0];
		// 当前用户任务ID
		String taskId = "";
		if(rowMsgs.length>=2){
			taskId = rowMsgs[1];
		}
		row.setValue(Constants.FIELD_TASK_ID, taskId);
		// 当前用户任务名称
		String taskState = "";
		if(rowMsgs.length>=3){
			taskState = rowMsgs[2];
		}
		row.setValue(Constants.FIELD_TASK_STATE, taskState);
		// 当前任务审批人
		String taskAssignees = "";
		if(rowMsgs.length>=4){
			taskAssignees = rowMsgs[3];
		}
		row.setValue(Constants.FIELD_TASK_ASSIGNEES, taskAssignees);
		// 接下来的任务以及任务审批人
		String taskNextAssignees = "";
		if(rowMsgs.length>=5){
			taskNextAssignees = rowMsgs[4];
		}
		row.setValue(Constants.FIELD_NEXT_ASSIGNEES, taskNextAssignees);
		// 流程参于者
		String assigneesUser = "";
		if(rowMsgs.length>=6){
			assigneesUser = rowMsgs[5];
		}
		row.setValue(Constants.FIELD_ASSIGNEE_USERS, assigneesUser);
		// 流程是否可删除，默认为第一个节点时，可删除流程
		String canDel = "";
		if(rowMsgs.length>=7){
			canDel = rowMsgs[6];
		}
		row.setValue(Constants.FIELD_CANDEL, canDel);
	}

	/**
	 * 验让当前用户是否有当前节点的审批权限
	 */
	private void checkTaskAssignees(RowBase rowBase, UserEntity user, String pDefId, Task task) {
		if(user==null){
			throw new BpmException("Session超时，请重新登录！");
		}
		
		// 超级管理员可审批所有流程
		if (user.getIsSuperAdmin()) {
			return;
		}

		// 当前可审批的用户
		String taskAssignees = this.getTaskAssignees(rowBase, task.getTaskDefinitionKey(), null);
		if (StringUtils.IsNullOrSpace(taskAssignees)) {
			// 没有可审批用户，则谁都可以审批
			return;
		}

		if (!taskAssignees.contains(user.getUserID())) {
			// 添加逻辑，如果节点配置中没有配置用户，也没有配置角色，则通过验证
			BpmTaskConfigRow configRow = BpmConfigCache.getTaskConfig(pDefId, task.getTaskDefinitionKey());
			if(configRow==null){
				return;
			}
			
			if(StringUtils.IsNullOrSpace(configRow.getTaskRole()) 
					&& StringUtils.IsNullOrSpace(configRow.getTaskUser())){
				return;
			}
			
			throw new BpmException("当前用户没有【" + task.getName() + "】的审批权限！");
		}
	}
	
	/**
	 * 获取当前任务的审批人
	 * @param rowBase
	 * @param taskKey
	 * @param listCopy
	 * @return
	 */
	private String getTaskAssignees(RowBase rowBase, String taskKey, List<String> listCopy){
		// 撤回流程的审批数据
		String assignees = (String)rowBase.getValue(GlobalDataType.String, 
				Constants.FIELD_TASK_ASSIGNEES);
		String[] taskUserList = assignees.split(":");
		// 找到当前的任务审批人
		String taskitem = "";
		for(String item : taskUserList){
			if(item.contains(taskKey)){
				taskitem = item;
				break;
			}
		}
		String[] users = taskitem.split(",");
		String workUsers = "";
		for(int i=2; i<users.length; i+=2){
			if(listCopy!=null){
				listCopy.add(users[i]);
			}
			workUsers += users[i] + "," + users[i+1] + ",";
		}
		if(workUsers!=""){
			workUsers = workUsers.substring(0, workUsers.length()-1);
		}
		return workUsers;
	}

	/**
	 * 获取当前节点信息
	 */
	private void getActiveTasksInfo(String pDefId, List<Task> nextTasks,
			RowBase rowBase, String exeId, Map<String, Object> comValues,
			UserEntity user) {
		if (nextTasks.size() <= 0) {
			// 流程状态名称
			rowBase.setValue(Constants.FIELD_TASK_STATE, "结束");
			rowBase.setValue(Constants.FIELD_TASK_ID, "U9");
			rowBase.setValue(Constants.FIELD_TASK_ASSIGNEES, "");
			// 流程是否可删除
			BpmTaskConfigRow configRow = BpmConfigCache.getTaskConfig(pDefId, "U9");
			if (configRow != null) {
				rowBase.setValue(Constants.FIELD_CANDEL, configRow.getTaskCanDel());
			} else {
				rowBase.setValue(Constants.FIELD_CANDEL, "0");
			}
		} else if (nextTasks.size() == 1) {
			Task nextTask = nextTasks.get(0);
			// 流程状态名称
			rowBase.setValue(Constants.FIELD_TASK_STATE, nextTask.getName());
			rowBase.setValue(Constants.FIELD_TASK_ID, nextTask.getTaskDefinitionKey());
			// 当前任务审批人
			HashMap<String, String> users = explicateUsers(pDefId,
					nextTask.getTaskDefinitionKey(), exeId, comValues, rowBase);
			if (users != null && users.size() > 0) {
				Set<String> userList = users.keySet();
				String userString = nextTask.getTaskDefinitionKey() + "," + nextTask.getName() + ",";
				for (String item : userList) {
					userString += item + "," + users.get(item) + ",";
				}
				if(userString!=""){
					userString = userString.substring(0, userString.length() - 1);
				}
				rowBase.setValue(Constants.FIELD_TASK_ASSIGNEES, userString);

				List<String> listCopy = new ArrayList<String>();
				listCopy.addAll(userList);

				// 设置任务的执行人
				taskService.setAssignee(nextTask.getId(), listCopy.get(0));
				// 添加任务的备选执行人
				for (int i = 1; i < listCopy.size(); i++) {
					taskService.addCandidateUser(nextTask.getId(), listCopy.get(i));
				}
				
			} else {
				rowBase.setValue(Constants.FIELD_TASK_ASSIGNEES,
								nextTask.getTaskDefinitionKey() + "," 
								+ nextTask.getName() + "," 
								+ user.getUserID() + "," + user.getUserRealName());
				// 设置任务的执行人
				taskService.setAssignee(nextTask.getId(), user.getUserID());
				// 添加任务的备选执行人
				taskService.addCandidateUser(nextTask.getId(), user.getUserID());
				// 领取一个任务
				taskService.claim(nextTask.getId(), user.getUserID());
			}

			// 流程是否可删除
			BpmTaskConfigRow taskConfig = BpmConfigCache.getTaskConfig(pDefId,
					nextTask.getTaskDefinitionKey());
			if (taskConfig != null) {
				rowBase.setValue(Constants.FIELD_CANDEL, taskConfig.getTaskCanDel());
			} else {
				rowBase.setValue(Constants.FIELD_CANDEL, "0");
			}

			// 处理当前节点的下级节点信息
			List<String> nPressList = new ArrayList<String>();
			if (taskConfig != null) {
				String nnextpress = taskConfig.getNNextPress();
				if (!StringUtils.IsNullOrSpace(nnextpress)) {
					String[] press = nnextpress.split(",");
					for (String item : press) {
						nPressList.add(item);
					}
				}
			}
			optionNextTask(pDefId, rowBase, exeId, comValues, nPressList, user);
		} else if (nextTasks.size() > 1) {
			String taskStates = "会签(";
			String taskIds = "";
			String taskUsers = "";
			boolean canDel = true;
			// 处理当前节点的下级节点信息
			List<String> nPressList = new ArrayList<String>();
			
			for(Task task : nextTasks){
				taskStates += task.getName() + ",";
				taskIds += task.getTaskDefinitionKey() + ",";
				
				// 当前任务审批人
				HashMap<String, String> users = explicateUsers(pDefId,
						task.getTaskDefinitionKey(), exeId, comValues, rowBase);
				if (users != null && users.size() > 0) {
					Set<String> userList = users.keySet();
					String userString = "";
					for (String item : userList) {
						userString += item + "," + users.get(item) + ",";
					}
					if(userString!=""){
						userString = userString.substring(0, userString.length() - 1);
					}
					taskUsers += task.getTaskDefinitionKey() + "," 
								+ task.getName() + "," + userString + ":";

					List<String> listCopy = new ArrayList<String>();
					listCopy.addAll(userList);

					// 设置任务的执行人
					taskService.setAssignee(task.getId(), listCopy.get(0));
					// 添加任务的备选执行人
					for (int i = 1; i < listCopy.size(); i++) {
						taskService.addCandidateUser(task.getId(), listCopy.get(i));
					}
					
				} else {
					taskUsers += task.getTaskDefinitionKey() + ","
							+ task.getName() + "," + user.getUserID() 
							+ "," + user.getUserRealName() + ":";
					// 设置任务的执行人
					taskService.setAssignee(task.getId(), user.getUserID());
					// 添加任务的备选执行人
					taskService.addCandidateUser(task.getId(), user.getUserID());
					// 领取一个任务
					taskService.claim(task.getId(), user.getUserID());
				}
				
				BpmTaskConfigRow taskConfig = BpmConfigCache.getTaskConfig(pDefId,
						task.getTaskDefinitionKey());
				// 流程是否可删除，所有的可删除，则为可删除
				if(canDel){
					if (taskConfig != null) {
						if(!taskConfig.getTaskCanDel().equals("1")){
							canDel = false;
						}
					} else {
						canDel = false;
					}
				}
				if (taskConfig != null) {
					String nnextpress = taskConfig.getNNextPress();
					if (!StringUtils.IsNullOrSpace(nnextpress)) {
						String[] press = nnextpress.split(",");
						for (String item : press) {
							if(!nPressList.contains(item)){
								nPressList.add(item);
							}
						}
					}
				}
			}
			
			// 流程状态名称
			taskStates = taskStates.substring(0, taskStates.length()-1) + ")";
			rowBase.setValue(Constants.FIELD_TASK_STATE, taskStates);
			taskIds = taskIds.substring(0, taskIds.length()-1);
			rowBase.setValue(Constants.FIELD_TASK_ID, taskIds);
			// 当前任务审批人
			taskUsers = taskUsers.substring(0, taskUsers.length()-1);
			rowBase.setValue(Constants.FIELD_TASK_ASSIGNEES, taskUsers);
			// 流程是否可删除
			if(canDel){
				rowBase.setValue(Constants.FIELD_CANDEL, "1");
			}else{
				rowBase.setValue(Constants.FIELD_CANDEL, "0");
			}
			
			optionNextTask(pDefId, rowBase, exeId, comValues, nPressList, user);
		}
		// 处理参于人
		assigneeUsers(rowBase, user.getUserID());
	}

	/**
	 * 处理下个节点信息
	 * 
	 * @param activitiId 活动节点
	 * @param pDefId 定义ID
	 * @param rowBase 数据行
	 * @param exeId   实例ID
	 * @param comValues
	 * @param nPressList
	 *            不处理的流程条件表达式
	 */
	private void optionNextTask(String pDefId, RowBase rowBase, String exeId,
			Map<String, Object> comValues, List<String> nPressList,
			UserEntity user) {
		List<TaskDefinition> taskDefintions = nextTaskDefinition(null, exeId, nPressList);
		if (taskDefintions == null || taskDefintions.size() <=0) {
			rowBase.setValue(Constants.FIELD_NEXT_ASSIGNEES, "");
			return;
		}
		
		// 会签情况下
		if(taskDefintions.size()>1){
			String taskAssignees = (String) rowBase.getValue(GlobalDataType.String,
					Constants.FIELD_TASK_ASSIGNEES);
			// 如果当前审核包含接下来的节点，说明是在会签中，但还没有过会签
			boolean isHQ = false;
			for(TaskDefinition taskDefintion : taskDefintions){
				String taskString = taskDefintion.getKey() + "," + taskDefintion.getNameExpression();
				if(taskAssignees.contains(taskString)){
					isHQ = true;
					break;
				}
			}
			if(isHQ){
				TaskDefinition taskDefintion = taskDefintions.get(0);
				taskDefintions = nextTaskDefinition(taskDefintion.getKey(), exeId, nPressList);
			}
		}
		
		String userString = "";
		for(TaskDefinition taskDefintion : taskDefintions){
			// 预获取下一步的审核人信息
			HashMap<String, String> users = explicateUsers(pDefId,
					taskDefintion.getKey(), exeId, comValues, rowBase);
			if (users == null || users.size() <= 0) {
				users = new HashMap<String, String>();
				users.put(user.getUserID(), user.getUserRealName());
			}

			// 任务key,任务名称,user1,username,user2,username:任务key,任务名称,user1,username,user2,username
			String taskString = taskDefintion.getKey() + "," + taskDefintion.getNameExpression() + ",";
			Set<String> userList = users.keySet();
			for (String item : userList) {
				taskString += item + "," + users.get(item) + ",";
			}
			taskString = taskString.substring(0, taskString.length()-1) + ":";
			userString += taskString;
		}
		if(userString != ""){
			userString = userString.substring(0, userString.length() - 1);
		}
		rowBase.setValue(Constants.FIELD_NEXT_ASSIGNEES, userString);
	}

	/**
	 * 根据流程ID查找当前任务节点
	 * 
	 * @param processDefinitionId
	 * @return
	 */
	private List<Task> findActiveTasksByProId(String proId) {
		List<Task> listTasks = taskService.createTaskQuery()
				.processInstanceId(proId).active().list();
		return listTasks;
	}

	/**
	 * 根据用户ID,查询用户所分配的任务
	 * 
	 * @param userid
	 * @return
	 */
	@SuppressWarnings("unused")
	private List<Task> findUserTasks(String userid) {
		List<Task> tasks = taskService.createTaskQuery()
				.taskCandidateUser(userid).list();
		return tasks;
	}

	/**
	 * 处理流程参与者
	 * 
	 * @param row
	 * @param userID
	 */
	private void assigneeUsers(RowBase rowBase, String userID) {
		if (StringUtils.IsNullOrSpace(userID)) {
			return;
		}

		String users = (String) rowBase.getValue(GlobalDataType.String,
				Constants.FIELD_ASSIGNEE_USERS);
		if (StringUtils.IsNullOrSpace(users)) {
			users = userID;
			rowBase.setValue(Constants.FIELD_ASSIGNEE_USERS, users);
		} else {
			String[] userlist = users.split(",");
			List<String> uList = new ArrayList<String>();
			for (String u : userlist) {
				uList.add(u);
			}
			if (!uList.contains(userID)) {
				users += userID + ",";
				rowBase.setValue(Constants.FIELD_ASSIGNEE_USERS, users);
			}
		}
	}

	/**
	 * 解释任务节点的执行人
	 * 
	 * @param pDefId
	 *            流程定义ID
	 * @param taskId
	 *            任务定义ID
	 * @param exeId
	 *            流程实例ID
	 * @param comValues
	 *            从流程配置中获取表单中的数据，做为脚本执行的参数之一
	 */
	private HashMap<String, String> explicateUsers(String pDefId,
			String taskId, String exeId, Map<String, Object> comValues,
			RowBase row) {

		// 第一步：用户指定的执行人做为下一步的执行人
		// 任务key,user1,username,user2,username:任务key,user1,username,user2,username
		String taskUsers = (String) row.getValue(GlobalDataType.String,
				Constants.FIELD_TASKUSER);
		if (!StringUtils.IsNullOrSpace(taskUsers)) {
			String[] tasks = taskUsers.split(":");
			for (String task : tasks) {
				String[] users = task.split(",");
				if (users.length <= 1) {
					continue;
				}
				String st = users[0];
				if (!StringUtils.IsNullOrSpace(st) && st.equals(taskId)) {
					HashMap<String, String> userList = new HashMap<String, String>();
					for (int i = 1; i < users.length;) {
						String user = users[i];
						String username = users[i + 1];
						if (!StringUtils.IsNullOrSpace(user)
								&& !userList.containsKey(user)) {
							userList.put(user, username);
						}
						i += 2;
					}
					return userList;
				}
			}
		}

		// 第二步：从配置中查找审核人
		return explicateUsersFormConfig(pDefId, taskId, exeId, comValues, row);
	}

	/**
	 * 从配置中解释出任务节点的执行人
	 * 
	 * @param 从流程配置中获取表单中的数据
	 *            ，做为脚本执行的参数之一
	 */
	private HashMap<String, String> explicateUsersFormConfig(String pDefId,
			String taskId, String exeId, Map<String, Object> comValues,
			RowBase row) {
		// 获取配置信息
		BpmTaskConfigRow taskConfig = BpmConfigCache.getTaskConfig(pDefId,
				taskId);
		// 没有配置信息，直接返回上一次执行人
		if (taskConfig == null) {
			HashMap<String, String> historyUserList = getHistoryUserList(
					taskId, exeId);
			return historyUserList;
		}

		// 获取用户配置
		String userExpress = taskConfig.getUserExpress();
		if (StringUtils.IsNullOrSpace(userExpress)) {
			userExpress = BpmConfigEditInterceptor.getUserExpress(taskConfig);
			taskConfig.setUserExpress(userExpress);
			BpmConfigEditInterceptor.updateTaskUserExpress(taskConfig,
					userExpress);
		}

		// userid,username,orgid
		HashMap<String, String> userOrg = new HashMap<String, String>();
		HashMap<String, String> userDept = new HashMap<String, String>();
		HashMap<String, String> userZq = new HashMap<String, String>();
		
		HashMap<String, String> userRealName = new HashMap<String, String>();
		if (!StringUtils.IsNullOrSpace(userExpress)) {
			String[] express1 = userExpress.split(",");
			if(express1.length % 5 == 0){
				for (int i = 0; i < express1.length;) {
					String userid = express1[i];
					String username = express1[i + 1];
					String orgid = express1[i + 2];
					String dept = express1[i+3];
					String zq = express1[i+4];

					userOrg.put(userid, orgid);
					userRealName.put(userid, username);
					userDept.put(userid, dept);
					userZq.put(userid, zq);
					i += 5;
				}
			}
		}

		String express = taskConfig.getSExpress();
		// 没有配置表达式，则所有的用户都是任务的用户
		if (StringUtils.IsNullOrSpace(express)) {
			// 有历史信息的，将历史信息中的审批人做为第一审批人
//			HashMap<String, String> historyUserList = getHistoryUserList(taskId,
//					exeId);
//			Set<String> keys = userRealName.keySet();
//			for (String key : keys) {
//				if (!historyUserList.containsKey(key)) {
//					historyUserList.put(key, userRealName.get(key));
//				}
//			}
			return userRealName;
		}

		// 处理公共数据
		// 处理业务表单数据 {业务表单字段}：从表单中所取值。所取字段在上级的“提取字段”中。
		if (comValues != null) {
			Set<String> keys = comValues.keySet();
			for (String key : keys) {
				String oldChar = "{" + key.toUpperCase().trim() + "}";
				Object obj = comValues.get(key);
				String newChar = "";
				if (obj == null) {
					newChar = "null";
				} else {
					newChar = obj.toString();
				}
				express = express.replace(oldChar, newChar);
			}
		}

		//		{JB_USERID}：经办用户ID。
		//		{JB_ORGID}：经办用户的机构ID。
		//		{JB_DEPTID}：经办用户的部门ID。
		//		{JB_ZQID}：经办用户的政区ID。
		String applyname = (String) row.getValue(GlobalDataType.String,
				Constants.FIELD_APPLYNAME);
		express = express.replace("{JB_USERID}", applyname);
		IQueryMap map = new QueryMap();
		map.getWhereMap().put(UserEntity.FIELD_USERID, applyname);
		UserEntity applyUser = UserService.getSingleRef().getEntity(UserEntity.class, map);
		if(applyUser!=null){
			express = express.replace("{JB_ORGID}", applyUser.getOrgID());
			express = express.replace("{JB_DEPTID}", applyUser.getDEPTID());
			express = express.replace("{JB_ZQID}", applyUser.getZqID());
		}else{
			express = express.replace("{JB_ORGID}", "''");
			express = express.replace("{JB_DEPTID}", "''");
			express = express.replace("{JB_ZQID}", "''");
		}

		HashMap<String, String> okList = new HashMap<String, String>();
		Set<String> userList = userOrg.keySet();
		ScriptEngineManager factory = new ScriptEngineManager();
		ScriptEngine scriptEngine = factory.getEngineByName("javascript");
		
		for (String user : userList) {
			String expressCopy = express;
			
			//		{SP_USERID}：审批用户ID。
			//		{SP_ORGID}：审批用户的机构ID。
			//		{SP_DEPTID}：审批用户的部门ID。
			//		{SP_ZQID}：审批用户的政区ID。
			
			// 处理{USERID}：需要判断是否有权限的用户ID。
			expressCopy = expressCopy.replace("{SP_USERID}", user);
			
			// 处理{ORGID}：需要判断是否有权限的用户的所在部门ID。
			String org = userOrg.get(user);
			expressCopy = expressCopy.replace("{SP_ORGID}", org);
			
			String dept = userDept.get(user);
			expressCopy = expressCopy.replace("{SP_DEPTID}", dept);
			
			String zq = userZq.get(user);
			expressCopy = expressCopy.replace("{SP_ZQID}", zq);
			
			// 用户名 
			String userName = userRealName.get(user);

			try {
				Object obj = scriptEngine.eval(expressCopy);
				if (obj != null && obj instanceof Boolean && (Boolean) obj) {
					okList.put(user, userName);
				}else if(!(obj instanceof Boolean)){
					Invocable inv = (Invocable) scriptEngine;
					obj = (Object) inv.invokeFunction("test");
					if (obj != null && obj instanceof Boolean && (Boolean) obj) {
						okList.put(user, userName);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
		}

//		Set<String> keys = okList.keySet();
//		for (String key : keys) {
//			if (!historyUserList.containsKey(key)) {
//				historyUserList.put(key, okList.get(key));
//			}
//		}

		return okList;
	}

	private HashMap<String, String> getHistoryUserList(String taskId,
			String exeId) {
		// 先从审批历史中查找审核人
		IQueryMap queryMap = new QueryMap();
		queryMap.setSelectFields(BpmHistoryRow.FIELD_ASSIGNEESID + ","
				+ BpmHistoryRow.FIELD_ASSIGNEES);
		queryMap.getWhereMap().put(BpmHistoryRow.FIELD_SExeid, exeId);
		queryMap.getWhereMap().put(BpmHistoryRow.FIELD_STAKID, taskId);
		queryMap.getOrderByMap().put(BpmHistoryRow.FIELD_SOptiontime, 0);
		BpmHistoryRow historyRow = BpmHistoryTable.getSingleRef().getEntity(
				BpmHistoryRow.class, queryMap);
		HashMap<String, String> historyUserList = new HashMap<String, String>();
		if (historyRow != null) {
			String user = historyRow.getAssigneesId();
			String username = historyRow.getAssignees();

			if (!StringUtils.IsNullOrSpace(user)) {
				historyUserList.put(user, username);
			}
		}
		return historyUserList;
	}

	/**
	 * 根据实例编号查找下一个任务节点
	 * 
	 * @param procInstId ：实例编号
	 * @param activitiId : 当前活动节点
	 * @return
	 */
	private List<TaskDefinition> nextTaskDefinition(String activitiId, String procInstId,
			List<String> nPressList) {
		// 流程定义
		String processDefinitionId = historyService
				.createHistoricProcessInstanceQuery()
				.processInstanceId(procInstId).singleResult()
				.getProcessDefinitionId();

		ProcessDefinitionEntity def = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
				.getDeployedProcessDefinition(processDefinitionId);
		// 执行实例
		ExecutionEntity execution = (ExecutionEntity) runtimeService
				.createProcessInstanceQuery().processInstanceId(procInstId)
				.singleResult();
		// 当前实例的执行到哪个节点
		if(StringUtils.IsNullOrSpace(activitiId)){
			activitiId = execution.getActivityId();
		}
		// 获得当前任务的所有节点
		List<ActivityImpl> activitiList = def.getActivities();
		String id = null;
		for (ActivityImpl activityImpl : activitiList) {
			id = activityImpl.getId();
			if (activitiId.equals(id)) {
				return nextTaskDefinition(activityImpl, nPressList);
			}
		}
		return null;
	}

	/**
	 * 下一个任务节点
	 * 
	 * @param activityImpl 当前节点
	 * @param elString 确定提交或通过的表达式
	 * @return
	 */
	private List<TaskDefinition> nextTaskDefinition(ActivityImpl activityImpl, List<String> nPressList) {
		// 当前任务的出节点
		List<PvmTransition> outTransitions = activityImpl.getOutgoingTransitions();
		// 外出节点
		List<PvmTransition> outTransitionsTemp = null;
		// 返回值
		List<TaskDefinition> arrayList = new ArrayList<TaskDefinition>();
		
		// 所有的下面节点
		for (PvmTransition tr : outTransitions) {
			// 出节点
			PvmActivity ac = tr.getDestination(); // 获取线路的终点节点
			// 判断节点
			if ("exclusiveGateway".equals(ac.getProperty("type"))) {
				// 多出节点
				outTransitionsTemp = ac.getOutgoingTransitions();
				if (outTransitionsTemp.size() == 1) {
					PvmActivity out = outTransitionsTemp.get(0).getDestination();
					if ("userTask".equals(out.getProperty("type"))){
						TaskDefinition taskDefinition = ((UserTaskActivityBehavior) ((ActivityImpl) out)
								.getActivityBehavior()).getTaskDefinition();
						arrayList.add(taskDefinition);
					} else {
						List<TaskDefinition> tempList = nextTaskDefinition((ActivityImpl) out, nPressList);
						arrayList.addAll(tempList);
					}
				} else if (outTransitionsTemp.size() > 1) {
					for (PvmTransition tr1 : outTransitionsTemp) {
						Object s = tr1.getProperty("conditionText");
						if(s==null){
							s = "";
						}
						String c = s.toString().trim();
						if (!nPressList.contains(c)) {
							PvmActivity out = tr1.getDestination();
							if ("userTask".equals(out.getProperty("type"))){
								TaskDefinition taskDefinition = ((UserTaskActivityBehavior) ((ActivityImpl) out)
										.getActivityBehavior()).getTaskDefinition();
								arrayList.add(taskDefinition);
							} else {
								List<TaskDefinition> tempList = nextTaskDefinition((ActivityImpl) out, nPressList);
								arrayList.addAll(tempList);
							}
						}
					}
				}
			} else if ("userTask".equals(ac.getProperty("type"))) {
				TaskDefinition taskDefinition = ((UserTaskActivityBehavior) ((ActivityImpl) ac)
						.getActivityBehavior()).getTaskDefinition();
				arrayList.add(taskDefinition);
			} else if ("parallelGateway".equals(ac.getProperty("type"))) {
				List<TaskDefinition> tempList = nextTaskDefinition((ActivityImpl) ac, nPressList);
				arrayList.addAll(tempList);
			} else {
				logger.info("nextTaskDefinition 未处理的流程类型：" + ac.getProperty("type"));
			}
		}
		return arrayList;
	}

	/**
	 * 跳转至指定活动节点
	 * 
	 * @param targetTaskDefinitionKey
	 * @throws Exception
	 */
	private void jump(String processId, String targetTaskDefinitionKey) {
		Command<Object> cmd = new JumpActivityCmd(processId,
				targetTaskDefinitionKey);
		processEngine.getManagementService().executeCommand(cmd);
	}
	
	/**
	 * 根据流程实例，获取流程定义key
	 * @param exeId
	 * @return
	 */
	@Override
	public String getProcessDefinitionKey(String exeId) {
		// 流程已经结束
		ProcessInstance processInstance = runtimeService
				.createProcessInstanceQuery().processInstanceId(exeId)
				.singleResult();
		if (processInstance == null) {
			return "";
		}
		return processInstance.getProcessDefinitionKey();
	}
	
	/**
	 * 流程处理(通过，不通过)通知事件
	 * @param row 数据实体对象
	 * @param taskOption 流程操作
	 * @param taskOptionContent 流程操作内容
	 * @param taskAssigneesId 当前任务的审批人ID
	 * @param taskAssigneesName 当前任务的审批人名称
	 * @param taskId 当前任务ID
	 * @param taskPId 上一任务ID
	 * @param taskPDefinitionKey 任务下节点定义ID
	 * @param taskPState 任务下节点状态
	 * @param isSuccessFinsh 是否正常结束
	 * @return
	 */
	public static void handelOption(ITable pTable, RowBase row, 
			String taskOption, String taskOptionContent, 
			String taskAssigneesId, String taskAssigneesName,
			String taskId, String taskPId, 
			String taskPDefinitionKey, String taskPState,
			boolean isSuccessFinsh, IWorkFlowCompont workFlowCompont){
		OptionInfo info = getOptionInfo(pTable, row, 
				taskOption, taskOptionContent, 
				taskAssigneesId, taskAssigneesName,
				taskId, taskPId, 
				taskPDefinitionKey, taskPState,
				isSuccessFinsh, workFlowCompont);
		BpmHandleOptionBase.editOption(info);
	}
	
	/**
	 * 工作流等待事件接口
	 * @param row 数据实体对象
	 * @param taskOption 流程操作
	 * @param taskOptionContent 流程操作内容
	 * @param taskAssigneesId 当前任务的审批人ID
	 * @param taskAssigneesName 当前任务的审批人名称
	 * @param taskId 当前任务ID
	 * @param taskPId 上一任务ID
	 * @param taskPDefinitionKey 任务下节点定义ID
	 * @param taskPState 任务下节点状态
	 * @param isSuccessFinsh 是否正常结束
	 * @return
	 */
	public static void waitOption(ITable pTable, RowBase row, 
			String taskOption, String taskOptionContent, 
			String taskAssigneesId, String taskAssigneesName,
			String taskId, String taskPId, 
			String taskPDefinitionKey, String taskPState,
			boolean isSuccessFinsh, IWorkFlowCompont workFlowCompont){
		OptionInfo info = getOptionInfo(pTable, row, 
				taskOption, taskOptionContent, 
				taskAssigneesId, taskAssigneesName,
				taskId, taskPId, 
				taskPDefinitionKey, taskPState,
				isSuccessFinsh, workFlowCompont);
		BpmWaitOptionBase.editOption(info);
	}
	
	/**
	 * 获取流程操作对象
	 * @param row 数据实体对象
	 * @param taskOption 流程操作
	 * @param taskOptionContent 流程操作内容
	 * @param taskAssigneesId 当前任务的审批人ID
	 * @param taskAssigneesName 当前任务的审批人名称
	 * @param taskId 当前任务ID
	 * @param taskPId 上一任务ID
	 * @param taskPDefinitionKey 任务下节点定义ID
	 * @param taskPState 任务下节点状态
	 * @param isSuccessFinsh 是否正常结束
	 * @return
	 */
	public static OptionInfo getOptionInfo(ITable pTable, RowBase row, 
				String taskOption, String taskOptionContent, 
				String taskAssigneesId, String taskAssigneesName,
				String taskId, String taskPId, 
				String taskPDefinitionKey, String taskPState,
				boolean isSuccessFinsh, IWorkFlowCompont workFlowCompont){
		OptionInfo info = new OptionInfo();
		// 流程定义ID
		info.BpmId = (String)row.getValue(GlobalDataType.String, Constants.FIELD_DEFINID);
		// 流程实例ID
		info.TaskProid = (String)row.getValue(GlobalDataType.String, Constants.FIELD_PROID);
		// 当前用户任务执行ID
		info.TaskId = taskId;
		// 当前用户任务定义ID
		info.TaskDefinitionKey = (String)row.getValue(GlobalDataType.String, Constants.FIELD_TASK_ID);
		// 当前用户任务名称
		info.TaskState = (String)row.getValue(GlobalDataType.String, Constants.FIELD_TASK_STATE);
		// 当前任务审批人
		info.TaskAssignees = (String)row.getValue(GlobalDataType.String, Constants.FIELD_TASK_ASSIGNEES);
		// 接下来的任务以及任务审批人
		info.TaskNextAssignees = (String)row.getValue(GlobalDataType.String, Constants.FIELD_NEXT_ASSIGNEES);
		// 流程发启人
		info.TaskApplyName = (String)row.getValue(GlobalDataType.String, Constants.FIELD_APPLYNAME);
		// 流程参于者
		info.TaskAssigneeUsers = (String)row.getValue(GlobalDataType.String, Constants.FIELD_ASSIGNEE_USERS);
		// 流程操作
		info.TaskOption = taskOption;
		// 流程操作内容
		info.TaskOptionContent = taskOptionContent;
		// 当前任务的审批人ID
		info.TaskAssigneesId = taskAssigneesId;
		// 当前任务的审批人名称
		info.TaskAssigneesName = taskAssigneesName;
		// 上一用户任务执行ID
		info.TaskPId = taskPId;
		// 上一用户任务定义ID
		info.TaskPDefinitionKey = taskPDefinitionKey;
		// 上一用户任务名称
		info.TaskPState = taskPState;
		// 是否成功结束
		info.IsSuccessFinsh = isSuccessFinsh;
		// 业务数据对象
		info.BusinessRow = row;
		// 流程处理对象
		info.workFlowCompont = workFlowCompont;
		// 业务表
		info.pTable = pTable;
		
		return info;
	}
}